package com.governtalk.backend.repository;

import com.governtalk.backend.entity.BrowseHistory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface BrowseHistoryRepository extends JpaRepository<BrowseHistory, Long> {
    
    // 根据用户ID获取浏览历史
    Page<BrowseHistory> findByUserIdOrderByBrowseTimeDesc(Long userId, Pageable pageable);
    
    // 根据用户ID和内容类型获取浏览历史
    Page<BrowseHistory> findByUserIdAndContentTypeOrderByBrowseTimeDesc(
        Long userId, BrowseHistory.ContentType contentType, Pageable pageable);
    
    // 根据用户ID和关键词搜索浏览历史
    @Query("SELECT h FROM BrowseHistory h WHERE h.userId = :userId AND " +
           "(h.contentTitle LIKE CONCAT('%', :keyword, '%') OR h.contentDescription LIKE CONCAT('%', :keyword, '%')) " +
           "ORDER BY h.browseTime DESC")
    Page<BrowseHistory> findByUserIdAndKeyword(@Param("userId") Long userId, 
                                               @Param("keyword") String keyword, 
                                               Pageable pageable);
    
    // 根据用户ID和内容ID查找特定浏览记录
    BrowseHistory findByUserIdAndContentTypeAndContentId(Long userId, 
                                                         BrowseHistory.ContentType contentType, 
                                                         Long contentId);
    
    // 删除用户的所有浏览历史
    void deleteByUserId(Long userId);
    
    // 删除用户特定类型的浏览历史
    void deleteByUserIdAndContentType(Long userId, BrowseHistory.ContentType contentType);
    
    // 获取用户最近浏览的内容
    List<BrowseHistory> findTop10ByUserIdOrderByBrowseTimeDesc(Long userId);
    
    // 根据时间范围获取浏览历史
    Page<BrowseHistory> findByUserIdAndBrowseTimeBetweenOrderByBrowseTimeDesc(
        Long userId, LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);
}
